<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Level;
use Yansongda\Pay\Pay;
use App\Utils\VipIndex;
use App\Models\VipOrder;
use App\Models\VipRecord;
use App\Models\UserRecharge;
use Illuminate\Http\Request;
use App\Http\Models\PayRequest;
use App\Models\AlipayVerifyOrder;
use Illuminate\Support\Facades\DB;

class AlipayController extends Controller
{
    public function pay(Request $request)
    {
        $order = PayRequest::create([
            'id_user' => strtoupper(str_random(6)) . date('YdmHis', time()),
            'body_stake' => $request->price,
            'body_gateway' => 'alipay',
        ]);
        $aliPayOrder = [
            'out_trade_no' => $order->id_user,
            'total_amount' => $order->body_stake, // 支付金额
            'subject'      => $request->subject ?? '充值' // 备注
        ];
        $config = config('alipay.pay');
        return Pay::alipay($config)->wap($aliPayOrder);
    }

    public function success()
    {
        return view('apps.paySuccess');
    }

    public function notify(Request $request)
    {
        $configs = config('alipay');
        $config = [];
        foreach ($configs as $value) {
            if ($value['app_id'] == $request->app_id) {
                $config = $value;
            }
        }
        $alipay = Pay::alipay($config);
        $verify = $alipay->verify();
        if (isset($verify)) {
            $order = PayRequest::where('id_user', $request->out_trade_no)->first();
            if ($request->trade_status == 'TRADE_SUCCESS' && $request->notify_type == 'trade_status_sync' && isset($order) && $order->status == 0) {
                DB::beginTransaction();  //开启事务
                try {
                    $order->body_transfer_number = $request->trade_no;
                    $order->gmt_payment = $request->gmt_payment;
                    $order->status = 1;
                    $order->save();
                    DB::commit();
                } catch (Exception $e) {
                    DB::rollback();
                }
            }

            if ($request->trade_status == 'TRADE_CLOSED') {
                \Log::info('交易关闭');
            }
            \Log::info('订单编号:' . $request->out_trade_no);
        }

        return $alipay->success();
    }

}
